package com.xinxin.servlet.day501;

import jakarta.servlet.*;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.*;

public class StudentServlet implements Servlet {
    @Override
    public void init(ServletConfig servletConfig) throws ServletException {

    }

    @Override
    public ServletConfig getServletConfig() {
        return null;
    }

    @Override
    public void service(ServletRequest servletRequest, ServletResponse servletResponse)
            throws ServletException, IOException {
        //设置响应的内容类型
        servletResponse.setContentType("student/html");
        PrintWriter out = servletResponse.getWriter();
        //这里可以链接数据库（JDBC）
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;

        //注册驱动
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            //获取链接
            String url = "jdbc:mysql://localhost:3306/test1";
            String user= "root";
            String password = "123456";
            conn= DriverManager.getConnection(url,user,password);
            //获取预编译的数据库操作对象
            String sql = "select name ,locate from campus";
            ps =conn.prepareStatement(sql);
            //执行sql
            rs = ps.executeQuery();
            //处理结果集
            while(rs.next()){
                String name = rs.getString("name");
                String locate =rs.getString("locate");
                out.print(name + "," +locate + "<br>");
            }

        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }finally {
            //释放资源
            if(rs !=null){
                try {
                    rs.close();
                } catch (SQLException e) {
                    throw new RuntimeException(e);
                }
            }
            if(ps !=null){
                try {
                    ps.close();
                } catch (SQLException e) {
                    throw new RuntimeException(e);
                }
            }

            if(conn !=null){
                try {
                    conn.close();
                } catch (SQLException e) {
                    throw new RuntimeException(e);
                }
            }
        }


    }

    @Override
    public String getServletInfo() {
        return null;
    }

    @Override
    public void destroy() {

    }
}
